package com.xiang.activity;

import java.util.List;

import com.xiang.adapter.DealListAdapter;
import com.xiang.constant.DealBaseInfo;
import com.xiang.entity.FindDealsEntity;
import com.xiang.seemovies.R;
import com.xiang.utils.ActivityJumpUril;
import com.xiang.utils.JsonUtil;
import com.xiang.utils.sharedpreferencesUtil;
import com.xiang.view.PullToRefreshView;
import com.xiang.view.PullToRefreshView.OnFooterRefreshListener;
import com.xiang.view.PullToRefreshView.OnHeaderRefreshListener;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.fzxy.zxy.niceday.AsyncHttpGet;
import cn.edu.fzxy.zxy.niceday.DefaultThreadPool;
import cn.edu.fzxy.zxy.niceday.RequestResultCallback;
import cn.edu.fzxy.zxy.niceday.examples.BaseActivity;

/**
 * 按照地理位置、分类、关键词等多种条件搜索团购信息，并以分页形式返回
 * 
 * @author Administrator
 * 
 */
public class FindDealsActivity extends BaseActivity implements
		OnHeaderRefreshListener, OnFooterRefreshListener, OnClickListener {
	private String city = "深圳";
	private String region = "南山区";
	private String category = "电影";
	private sharedpreferencesUtil util;
	private List<DealBaseInfo> list;
	private ListView listview;
	private TextView txv_total_count;
	private DealListAdapter adapter;
	private int show_list = 10000;
	private myHandler handler;
	private RelativeLayout rl_change_city_layout;
	private int currenPage = 1;
	private int total_count = 0;// 找到的信息数
	private TextView txv_city;
	
	private ImageView refresh;
	private ProgressBar refreshProgressbar;

	private long exitTime = 0;

	private PullToRefreshView mPullToRefreshView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_deal_layout);
		initView();
		request();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (handler == null) {
			handler = new myHandler();
		}
		getCityInfo();
	}

	private void initView() {
		txv_city = (TextView) findViewById(R.id.main_city);
		refresh = (ImageView) findViewById(R.id.find_deal_refresh_img);
		refresh.setOnClickListener(this);
		refreshProgressbar = (ProgressBar) findViewById(R.id.find_deal_progressbar);
		txv_total_count = (TextView) findViewById(R.id.txv_main_total_count);
		mPullToRefreshView = (PullToRefreshView) findViewById(R.id.main_pull_refresh_view);
		listview = (ListView) findViewById(R.id.find_deal_list);
		listview.setOnItemClickListener(new itemClickListener());
		rl_change_city_layout = (RelativeLayout) findViewById(R.id.rl_change_city);
		rl_change_city_layout
				.setOnClickListener(new RelativeLayout.OnClickListener() {
					@Override
					public void onClick(View v) {
						ActivityJumpUril
								.findDealToGetCities(FindDealsActivity.this);
						overridePendingTransition(R.anim.right_in, R.anim.left_out);
					}
				});
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
	}

	class itemClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			DealBaseInfo baseinfo = list.get(arg2);
			ActivityJumpUril.findDealToDealDetail(FindDealsActivity.this,
					baseinfo);
			overridePendingTransition(R.anim.right_in, R.anim.left_out);
		}

	}

	private void showList() {
		if (adapter == null) {
			adapter = new DealListAdapter(FindDealsActivity.this, list);
			listview.setAdapter(adapter);
		} else {
			adapter.resetData(list);
			adapter.notifyDataSetChanged();
		}
	}

	class myHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			refresh.setVisibility(View.VISIBLE);
			refreshProgressbar.setVisibility(View.GONE);
			
			mPullToRefreshView.onHeaderRefreshComplete();
			mPullToRefreshView.onFooterRefreshComplete();
			if (msg.what == show_list) {
				txv_total_count.setText("共有" + total_count + "条信息");
				showList();
			}
		}
	}

	private void getCityInfo() {
		if (util == null) {
			util = new sharedpreferencesUtil(FindDealsActivity.this);
		}
		String _city = util.getCity();
		String _region = util.getRegion();
		if (!(_city.equals(""))) {
			city = _city;
			txv_city.setText(city);
		}
		if (!(_region.equals(""))) {
			region = _region;
		}
	}

	private void request() {
		refresh.setVisibility(View.GONE);
		refreshProgressbar.setVisibility(View.VISIBLE);
		getCityInfo();
		FindDealsEntity entity = new FindDealsEntity(city);
		entity.region = region;
		entity.category = category;
		entity.page = currenPage + "";
		AsyncHttpGet get = new AsyncHttpGet(null, entity.getUrl(),
				entity.getParameterList(), new RequestResultCallback() {

					@Override
					public void onSuccess(Object o) {
						System.out.println("#########result: " + o.toString());
						if (currenPage > 1) {
							List<DealBaseInfo> newList = JsonUtil
									.analysisDeal(o.toString());
							if (list != null) {
								list.addAll(newList);
							}
						} else {
							list = JsonUtil.analysisDeal(o.toString());
						}
						total_count = JsonUtil.analysisDeal_count(o.toString());
						System.out.println("########total_count: "
								+ total_count);

						Message msg = new Message();
						msg.what = show_list;
						handler.sendMessage(msg);
					}

					@Override
					public void onFail(Exception e) {
						System.out.println("#########Exception");

					}
				});
		DefaultThreadPool.getInstance().execute(get);
		this.requestList.add(get);
	}

	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		currenPage++;
		request();
	}

	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		currenPage = 1;
		request();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if ((System.currentTimeMillis() - exitTime) > 2000) {
				Toast.makeText(getApplicationContext(), "再按一次退出程序",
						Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis();
			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.find_deal_refresh_img:
			request();
			break;

		default:
			break;
		}
	}
}
